# Copyright (C) 2007 "dbsolution sas" 
#
# This file is part of Weebotee.
#
# Weebotee is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Weebotee is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Weebotee.  If not, see <http://www.gnu.org/licenses/>.

import datetime
from random import randint
from django.db import models
from django.db.models import Q
from django.template.defaultfilters import slugify
from django.contrib.auth.models import User, Group

STATUS_CHOICES = [(0, 'Privato'), (1, 'Shared'), (2, 'Da approvare'), (3, 'Pubblico'),]

class SectionManager(models.Manager):
    def getSections(self,user):
        if user.is_authenticated():
            return Section.objects.filter(Q(status__exact=3)| Q(owner__exact=user) & Q(status__exact=0) |
                                          Q(status__exact=1) & Q(group__in=user.groups.all())).distinct()
        else:
            return Section.objects.filter(status__exact=3)

    def getSection(self,user,slug):
        if user.is_authenticated():
            querySet = (
                Q(slug__exact=slug), 
                Q(status__exact=3) | Q(owner__exact=user) & Q(status__exact=0) |
                    Q(status__exact=1) & Q(group__in=user.groups.all()
                )
            )
            return Section.objects.filter(*querySet).distinct()[0]
        else:
            try:
                return Section.objects.filter(Q(slug__exact=slug), status__exact=3).distinct()[0]
            except:
                return None
    
    
    def getPending(self,user,element):
        if user.is_authenticated():
            return Element.objects.filter(etype__exact=element, owner__exact=user, status__exact=2)
        else:
            return []
        
    def getRelatedSection(self,user,parent):
        if user.is_authenticated():
            return Section.objects.filter(Q(status__exact=3)| Q(owner__exact=user) & Q(status__exact=0) |
                                          Q(status__exact=1) & Q(group__in=user.groups.all()), parent=parent).distinct()
        else:
            return Section.objects.filter(status__exact=3, parent=parent)

class Section(models.Model): 
    # Parametri descrittivi
    name = models.CharField(max_length=255)
    description = models.TextField(blank=True)
    status = models.IntegerField(choices=STATUS_CHOICES, default=0)
    order = models.IntegerField(default=0)
    stype = models.CharField(max_length=255, blank=True)
    
    creation_date = models.DateTimeField(editable=False)
    last_update = models.DateTimeField(editable=False)

    # Dipendenze
    parent = models.ForeignKey('self', null=True, blank=True, related_name='subsections')
    owner = models.ForeignKey(User)
    group = models.ManyToManyField(Group, null=True, blank=True)
    owner_alias = models.CharField(max_length=100, blank=True)
    viewtype = models.CharField(max_length=100)
        
    # SEO Metadata
    slug = models.SlugField()
    author = models.CharField(max_length=100, blank=True)
    pagetitle = models.CharField(max_length=100, blank=True)
    keywords = models.CharField(max_length=255, blank=True)
    metatags = models.TextField(blank=True)

    objects = SectionManager()
    
    def save(self):
        self.last_update = datetime.datetime.now()
        if not self.creation_date:
            self.creation_date = datetime.datetime.now()
        
        if self.slug == "": 
            self.slug = slugify(self.name)   
        else: 
            self.slug = slugify(self.slug)
            
        # wtf is that? (ndDark)    
        existingSlug = Section.objects.filter(slug__iexact=self.slug)
        while existingSlug.__len__() != 0 and existingSlug[0].id != self.id:
            self.slug += "-%d" %randint(0, 1000)
            existingSlug = Section.objects.filter(slug__iexact=self.slug)
            
        if self.stype == "":
            self.stype = "Section"
        super(Section, self).save()

    def __unicode__(self):
        return self.name
    
    class Meta:
        app_label = 'core'
        permissions = (
            ( "can_mod_perms", "Can Modify Permissions"),
            )
        
    class Admin:
        pass
